package main

import (
	"fmt"
	"io"
	"net"
	"sync"
	"time"
)

type Server struct {
	Ip   string
	Port int

	//在线用户列表
	OnlineMap map[string]*User
	mapLock   sync.RWMutex

	//消息广播的channel
	Message chan string
}

func NewServer(ip string, port int) *Server {
	server := &Server{
		Ip:        ip,
		Port:      port,
		OnlineMap: make(map[string]*User),
		Message:   make(chan string),
	}
	return server
}

// 广播消息的方法
func (this *Server) BroadCast(user *User, msg string) {
	sendMsg := "[" + user.Addr + "]" + user.Name + ":" + msg
	fmt.Println("即将要发送的消息为：", sendMsg)
	this.Message <- sendMsg

}

// 监听Message广播消息channel的froutine，一旦有东西就发送给全部在线的user
func (this *Server) LinstenMessage() {
	for {
		msg := <-this.Message
		//将message消息发送给全部在线的User
		fmt.Println("LinstenMessage 正在广播消息")
		this.mapLock.Lock()
		for _, cli := range this.OnlineMap {
			cli.C <- msg
		}
		this.mapLock.Unlock()
	}
}

func (this *Server) Handler(con net.Conn) {
	fmt.Println("连接建立成功")

	user := NewUser(con, this)

	user.Online()
	//接受客户端发送的消息
	//判断是否活跃
	islive := make(chan bool)

	go func() {
		buf := make([]byte, 4096)
		for {
			n, err := con.Read(buf)
			if n == 0 {
				user.Offline()
				return
			}
			if err != nil && err != io.EOF {
				fmt.Println("conn Read err:", err)
				return
			}

			//提取用户的消息
			msg := string(buf[:n-1])
			//将得到的消息进行广播
			user.DoMessage(msg)

			//用户的任意消息，代表当前用户是活跃的
			islive <- true

		}
	}()

	for {
		select {
		//当前用户是活跃的，重制定时器
		case <-islive:

		//超时处理
		case <-time.After(time.Minute * 10):
			//提出当前用户
			user.Offline()
			user.SendMsg("长时间未操作，自动下线")
			delete(this.OnlineMap, user.Name)
			close(user.C)
			con.Close()
			//推出当前handler
			return
		}
	}

}

func (this *Server) Start() {
	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", this.Ip, this.Port))
	if err != nil {
		fmt.Println("net.Listen err:", err)
		return
	}
	defer listener.Close()
	fmt.Println("start方法正在执行")

	//启动监听Message的groutine
	go this.LinstenMessage()
	for {
		fmt.Println("启动监听Message的groutine")
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("net.Listen err:", err)
			continue
		}
		go this.Handler(conn)
	}
}
